package Smt.BaseDao;

import Smt.Util.ConfigManager;

import java.sql.*;

public class BaseDao {

	private Connection con;//获得oracle链接
	private PreparedStatement ps;//
	private Statement stmt;//
	private ResultSet rs;

	public Connection getCon() {
		return con;
	}

	public void setCon(Connection con) {
		this.con = con;
	}

	public PreparedStatement getPs() {
		return ps;
	}

	public void setPs(PreparedStatement ps) {
		this.ps = ps;
	}

	public Statement getStmt() {
		return stmt;
	}

	public void setStmt(Statement stmt) {
		this.stmt = stmt;
	}

	public ResultSet getRs() {
		return rs;
	}

	public void setRs(ResultSet rs) {
		this.rs = rs;
	}

	public Connection getConn() {

		String driver = Smt.Util.ConfigManager.getInstance().getString("jdbc.driver_class");
		String url = ConfigManager.getInstance().getString("jdbc.connection.url");
		String username = ConfigManager.getInstance().getString("jdbc.connection.username");
		String password = ConfigManager.getInstance().getString("jdbc.connection.password");
		try {
			//1.加载驱动
			Class.forName(driver);
			//2.获得数据库
			con = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	public void closeAll() {
		try {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
			if (stmt != null)
				stmt.close();
			if (con != null)
				con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//获得数据总数目
	public int Count(String sql) {
		int num = 0;
		getConn();
		try {
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				num = rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeAll();
		}
		return num;
	}

	//增删改数据
	public boolean util(String sql, Object[] u) {

		try {
			ps = this.getConn().prepareStatement(sql);
			for (int i = 0; i < u.length; i++) {
				ps.setObject(i + 1, u[i]);
			}
			int p = ps.executeUpdate();
			if (p > 0)
				return true;
		} catch (SQLException e) {
			return false;
		} finally {
			this.closeAll();
		}
		return false;
	}

	//查询数据
	public ResultSet getList(String sql, Object[] u) {
		try {
			ps = this.getConn().prepareStatement(sql);
			if (u != null) {
				for (int i = 0; i < u.length; i++) {
					ps.setObject(i + 1, u[i]);
				}
			}
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
}
